import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva/index';
import {
  Spin,
  Row,
  Empty,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Table,
} from 'antd/lib/index';
import moment from 'moment/moment';
import router from 'umi/router';

import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
// import ExportJsonExcel from 'js-export-excel';
import ExportJsonExcel from '@/components/XLSXOUT/js-export-excel-custom';

import styles from '../../PositionSystem/FundPosition/Test.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

/* eslint react/no-multi-comp:0 */
@connect(({ billSituationRule, loading }) => ({
  billSituationRule,
  loading: loading.models.ruleTest,
}))
@Form.create()
class RYBillDangerSituation extends PureComponent {
  state = {
    filterData: [],
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    formValues: {
      productId: 1,
      billType: 0,
      orderItem: 0,
      orderType: 0,
      stock: '',
    }, // 查询菜单栏   查询参数

    modalVisible: false,
    updateModalVisible: false,

    selectedRows: [],

    stepFormValues: {},

    dataTradeList: {},
    updateParam: true,

    HistogramModalVisible: false,
    suggestions: [],
    textboxValues: {
      key: '',
      type: 1,
    },
  };

  excelData = [];

  indexCountColumns = [];

  excel2Data = [];

  indexCount2Columns = [];

  groupRender = (value, row, index) => {
    const obj = {
      children: value,
      props: {},
    };

    if (this.indexCountColumns.length > 0) {
      let isHave = false;
      for (let i = 0; i < this.indexCountColumns.length; i++) {
        if (index === this.indexCountColumns[i].index) {
          isHave = true;
          obj.props.rowSpan = this.indexCountColumns[i].count;
          // obj.props.colSpan = 0;
        }
      }
      if (!isHave) {
        if (value) {
          obj.props.rowSpan = 0;
          obj.props.colSpan = 0;
        } else {
          obj.props.rowSpan = 0;
          // obj.props.colSpan = 0;
        }
      }
    }
    return obj;
  };

  groupRender1 = (value, row, index) => {
    const obj = {
      children: value,
      props: {},
    };

    if (this.indexCount2Columns.length > 0) {
      let isHave = false;
      for (let i = 0; i < this.indexCount2Columns.length; i++) {
        if (index === this.indexCount2Columns[i].index) {
          isHave = true;
          obj.props.rowSpan = this.indexCount2Columns[i].count;
        }
      }
      if (!isHave) {
        if (value) {
          obj.props.rowSpan = 0;
          obj.props.colSpan = 0;
        } else {
          obj.props.rowSpan = 0;
        }
      }
    }
    return obj;
  };

  renderContentBase = (value, row, index) => {
    const obj = {
      children: value,
      props: {},
    };
    return obj;
  };

  columns = [
    {
      title: '股票名称',
      dataIndex: 'stockId',
      render: this.groupRender,
      key: 'stockId',
      // width:100,
    },
    {
      title: '执行价',
      dataIndex: 'strikePrice',
      render: this.renderContentBase,
      key: 'strikePrice',
      // width:130,
    },
    {
      title: '到期日',
      dataIndex: 'finalDate',
      render: this.renderContentBase,
      key: 'finalDate',
      // width:100,
    },
    {
      title: '现价和执行价比例',
      dataIndex: 'toStrikePriceRate',
      render: this.renderContentBase,
      key: 'toStrikePriceRate',
      // width:110,
    },
    {
      title: '票息',
      dataIndex: 'billCoupon',
      render: this.renderContentBase,
      key: 'billCoupon',
      // width:110,
    },

    {
      title: '票据金额(美金)',
      dataIndex: 'amountOfMoney',
      render: this.renderContentBase,
      key: 'amountOfMoney',
      // width:110,
    },
    {
      title: '总计预计接货金额（美金）',
      dataIndex: 'allBillValue',
      render: this.groupRender,
      key: 'allBillValue',
      // width:140,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      render: this.renderContentBase,
      key: 'remark',
      // width:110,
    },
  ];

  columns2 = [
    {
      title: '股票名称',
      dataIndex: 'stockId',
      render: this.groupRender1,
      key: 'stockId',
      // width:100,
    },
    {
      title: '执行价',
      dataIndex: 'strikePrice',
      render: this.renderContentBase,
      key: 'strikePrice',
      // width:130,
    },
    {
      title: '到期日',
      dataIndex: 'finalDate',
      render: this.renderContentBase,
      key: 'finalDate',
      // width:100,
    },
    {
      title: '现价和执行价比例',
      dataIndex: 'toStrikePriceRate',
      render: this.renderContentBase,
      key: 'toStrikePriceRate',
      // width:110,
    },
    {
      title: '票息',
      dataIndex: 'billCoupon',
      render: this.renderContentBase,
      key: 'billCoupon',
      // width:110,
    },

    {
      title: '票据金额(美金)',
      dataIndex: 'amountOfMoney',
      render: this.renderContentBase,
      key: 'amountOfMoney',
      // width:110,
    },
    {
      title: '预计接货金额（美金）',
      dataIndex: 'allBillValue',
      render: this.groupRender1,
      key: 'allBillValue',
      // width:140,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      render: this.renderContentBase,
      key: 'remark',
      // width:110,
    },
  ];

  // 默认加载数据-起始方法
  render() {
    const {
      billSituationRule: { dangerBill1data, dangerBill2data },
      loading,
      total,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      listLoading,
    } = this.state;
    const newdata = {
      list: [],
      pagination: '',
    };
    const newdata1 = {
      list: [],
      pagination: '',
    };
    if (dangerBill1data.code == 1) {
      newdata.list = dangerBill1data.list;
    }

    this.indexCountColumns = [];
    let indexTemp = 0;
    let countTemp = 1;
    for (let i = 0; i < newdata.list.length; i++) {
      newdata.list[i].key = `00${i}`;
      if (newdata.list[i].finalDate && newdata.list[i].finalDate.length > 10) {
        newdata.list[i].finalDate = newdata.list[i].finalDate.substring(0, 10);
      }
      if (newdata.list[i].billCoupon && newdata.list[i].billCoupon > 0) {
        newdata.list[i].billCoupon = `${parseFloat(newdata.list[i].billCoupon * 100).toFixed(2)}%`;
      }
      if (i > 0) {
        if (newdata.list[i].stockId === newdata.list[i - 1].stockId) {
          countTemp++;
          if (i === newdata.list.length - 1) {
            this.indexCountColumns.push({
              index: indexTemp,
              count: countTemp,
            });
          }
        } else {
          this.indexCountColumns.push({
            index: indexTemp,
            count: countTemp,
          });
          let sumAllBillValue = 0;
          for (let j = indexTemp; j < indexTemp + countTemp; j++) {
            sumAllBillValue += newdata.list[j].amountOfMoney;
          }
          newdata.list[indexTemp].allBillValue = sumAllBillValue;
          indexTemp = i;
          countTemp = 1;

          if (i === newdata.list.length - 1) {
            this.indexCountColumns.push({
              index: indexTemp,
              count: countTemp,
            });
          }
        }
      }
    }
    this.excelData = newdata;

    if (dangerBill2data.code == 1) {
      newdata1.list = dangerBill2data.list;
    }

    this.indexCount2Columns = [];
    let indexTemp1 = 0;
    let countTemp1 = 1;
    for (let i = 0; i < newdata1.list.length; i++) {
      newdata1.list[i].key = `00${i}`;
      if (newdata1.list[i].finalDate && newdata1.list[i].finalDate.length > 10) {
        newdata1.list[i].finalDate = newdata1.list[i].finalDate.substring(0, 10);
      }
      if (newdata1.list[i].billCoupon && newdata1.list[i].billCoupon > 0) {
        newdata1.list[i].billCoupon = `${parseFloat(newdata1.list[i].billCoupon * 100).toFixed(
          2
        )}%`;
      }
      if (i > 0) {
        if (newdata1.list[i].stockId === newdata1.list[i - 1].stockId) {
          countTemp1++;
          if (i === newdata1.list.length - 1) {
            this.indexCount2Columns.push({
              index: indexTemp1,
              count: countTemp1,
            });
          }
        } else {
          this.indexCount2Columns.push({
            index: indexTemp1,
            count: countTemp1,
          });
          let sumAllBillValue = 0;
          for (let j = indexTemp1; j < indexTemp1 + countTemp1; j++) {
            sumAllBillValue += newdata1.list[j].amountOfMoney;
          }
          newdata1.list[indexTemp1].allBillValue = sumAllBillValue;
          indexTemp1 = i;
          countTemp1 = 1;
          if (i === newdata1.list.length - 1) {
            this.indexCount2Columns.push({
              index: indexTemp1,
              count: countTemp1,
            });
          }
        }
      }
    }
    this.excel2Data = newdata1;

    return (
      <PageHeaderWrapper title="危险票据">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <h1
              style={{
                fontSize: 16,
                textAlign: 'center',
                paddingTop: this.tableHeadPadding,
                paddingBottom: this.tableHeadPadding,
              }}
            >
              （瑞银）已经跌破执行价的票据
            </h1>
            <Button style={{ top: 20, bottom: 30 }} onClick={this.downloadExcel}>
              导出（瑞银）已经跌破执行价的票据Excel表格
            </Button>
            <br />
            <br />
            <br />
            {newdata.list.length == 0 ? (
              <Empty />
            ) : (
              <Table
                style={{ top: 20 }}
                pagination={false}
                // scroll={{x:1500}}
                columns={this.columns}
                dataSource={newdata.list}
                bordered
              />
            )}
            <br />
            <br />
            <div>
              <h1
                style={{
                  fontSize: 16,
                  textAlign: 'center',
                  paddingTop: this.tableHeadPadding,
                  paddingBottom: this.tableHeadPadding,
                }}
              >
                （瑞银）距离执行价比例{'<=5%'}的票据
              </h1>
              <Button style={{ top: 20, bottom: 30 }} onClick={this.downloadExcel1}>
                导出（瑞银）距离执行价比例{'<=5%'}的票据Excel表格
              </Button>
            </div>
            <br />
            <br />
            {newdata1.list.length == 0 ? (
              <Empty />
            ) : (
              <Table
                style={{ top: 20 }}
                pagination={false}
                // scroll={{x:1500}}
                columns={this.columns2}
                dataSource={newdata1.list}
                bordered
              />
            )}

            <br />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }

  downloadExcel = () => {
    const data = this.excelData.list; // 表格数据
    const option = {};
    const dataTable = [];
    if (data) {
      for (const i in data) {
        if (data) {
          const obj = {
            股票名称: data[i].stockId,
            执行价: data[i].strikePrice,
            到期日: data[i].finalDate,
            现价和执行价比例: data[i].toStrikePriceRate,
            票息: data[i].billCoupon,
            '票据金额(美金)': data[i].amountOfMoney,
            '总计预计接货金额（美金）': data[i].allBillValue,
            备注: data[i].remark,
          };
          dataTable.push(obj);
        }
      }
    }
    const merges = [];
    if (this.indexCountColumns.length > 0) {
      for (let i = 0; i < this.indexCountColumns.length; i++) {
        merges.push(
          {
            s: { c: 0, r: this.indexCountColumns[i].index + 1 },
            e: { c: 0, r: this.indexCountColumns[i].index + this.indexCountColumns[i].count },
          },
          {
            s: { c: 6, r: this.indexCountColumns[i].index + 1 },
            e: { c: 6, r: this.indexCountColumns[i].index + this.indexCountColumns[i].count },
          }
        );
      }
    }
    option.merges = merges;
    option.fileName = '（瑞银）已经跌破执行价的票据';
    option.datas = [
      {
        sheetData: dataTable,
        sheetName: 'sheet',
        sheetFilter: [
          '股票名称',
          '执行价',
          '到期日',
          '现价和执行价比例',
          '票息',
          '票据金额(美金)',
          '总计预计接货金额（美金）',
          '备注',
        ],
        sheetHeader: [
          '股票名称',
          '执行价',
          '到期日',
          '现价和执行价比例',
          '票息',
          '票据金额(美金)',
          '总计预计接货金额（美金）',
          '备注',
        ],
        columnWidths: [
          { wpx: 85 },
          { wpx: 85 },
          { wpx: 105 },
          { wpx: 135 },
          { wpx: 85 },
          { wpx: 135 },
          { wpx: 185 },
          { wpx: 85 },
        ],
      },
    ];

    const toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  };

  downloadExcel1 = () => {
    const data = this.excel2Data.list; // 表格数据
    const option = {};
    const dataTable = [];
    if (data) {
      for (const i in data) {
        if (data) {
          const obj = {
            股票名称: data[i].stockId,
            执行价: data[i].strikePrice,
            到期日: data[i].finalDate,
            现价和执行价比例: data[i].toStrikePriceRate,
            票息: data[i].billCoupon,
            '票据金额(美金)': data[i].amountOfMoney,
            '预计接货金额（美金）': data[i].allBillValue,
            备注: data[i].remark,
          };
          dataTable.push(obj);
        }
      }
    }
    const merges = [];
    if (this.indexCount2Columns.length > 0) {
      for (let i = 0; i < this.indexCount2Columns.length; i++) {
        merges.push(
          {
            s: { c: 0, r: this.indexCount2Columns[i].index + 1 },
            e: { c: 0, r: this.indexCount2Columns[i].index + this.indexCount2Columns[i].count },
          },
          {
            s: { c: 6, r: this.indexCount2Columns[i].index + 1 },
            e: { c: 6, r: this.indexCount2Columns[i].index + this.indexCount2Columns[i].count },
          }
        );
      }
    }
    option.merges = merges;
    option.fileName = '（瑞银）距离执行价比例小于等于5%的票据';
    option.datas = [
      {
        sheetData: dataTable,
        sheetName: 'sheet',
        sheetFilter: [
          '股票名称',
          '执行价',
          '到期日',
          '现价和执行价比例',
          '票息',
          '票据金额(美金)',
          '预计接货金额（美金）',
          '备注',
        ],
        sheetHeader: [
          '股票名称',
          '执行价',
          '到期日',
          '现价和执行价比例',
          '票息',
          '票据金额(美金)',
          '预计接货金额（美金）',
          '备注',
        ],
        columnWidths: [
          { wpx: 85 },
          { wpx: 85 },
          { wpx: 105 },
          { wpx: 135 },
          { wpx: 85 },
          { wpx: 135 },
          { wpx: 155 },
          { wpx: 85 },
        ],
      },
    ];

    const toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  };

  // 加载完 之后 再加载 此 方法
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'billSituationRule/DangerBill1',
      payload: formValues,
      callback: response => {
        let sumAmountOfMoney = 0;
        for (let i = 0; i < response.list.length; i++) {
          sumAmountOfMoney += parseFloat(response.list[i].amountOfMoney);
        }
        response.list.push({
          stockId: '总计',
          allBillValue: sumAmountOfMoney,
        });
      },
    });

    dispatch({
      type: 'billSituationRule/DangerBill2',
      payload: formValues,
      callback: response => {
        let sumAmountOfMoney = 0;
        for (let i = 0; i < response.list.length; i++) {
          sumAmountOfMoney += parseFloat(response.list[i].amountOfMoney);
        }
        response.list.push({
          stockId: '总计',
          allBillValue: sumAmountOfMoney,
        });
      },
    });
  }
}
export default RYBillDangerSituation;
